import { inject, observer } from 'mobx-react';
import equal from "deep-equal"
import { toJS } from "mobx"
import { WeaAlertPage, WeaErrorPage, WeaTools, WeaFormItem, WeaBrowser, WeaUpload, WeaRightMenu, WeaNewScroll, WeaError, WeaTextarea } from "ecCom"
import { Button, Select, Icon, Form, Input, Modal, Spin, Row, Col, Radio, Tooltip } from "antd";
const Option = Select.Option;
// import WorkPlan from "weaWorkplan"
// const WorkPlanCreate = WorkPlan.com.WorkPlanCreate;
import CrmSearchGroup from '../comp/crm-show-group'
import ViewContactLog from "./ViewContactLog"
import { crmAddFormRules } from '../../util/index';
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
@observer
class CustomerContact extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            contacterId: "",
            sellChanceId: "",
            ascSort: true,
            relatedfile: "",
            relatedimgs: "",
            relateddoc: "",
            relatedwf: "",
            relatedprj: "",
            isrefresh: 0,
            rowHeight: 1,
            value: "",
            visible: false,
            crmArr: [],
            selectType: "info",//plan 联系计划; info联系情况
            workplanLoaded: false,
            contactWayId: "",
            value:"",
            workPlanTab: "1"
        }
    }

    componentDidMount() {
        this.doInit();
        if (window.weaWorkplan) {
            //search 查询客户  monitor 客户监控  assign 客户分配  share 批量共享  hrmView?searchHrmId=186  人员卡片过来的  //report客户信息
            //report 客户信息
            this.setState({ workplanLoaded: true });
        } else {
            // 异步加载别模块的静态资源
            eventRegister.loadModule('f_workplan', () => {
                // 加载成功
                //search 查询客户  monitor 客户监控  assign 客户分配  share 批量共享  hrmView?searchHrmId=186  人员卡片过来的  //report客户信息
                //report 客户信息
                this.setState({ workplanLoaded: true });
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载日程模块失败，请联系系统管理员！");
            });
        }
    }

    componentWillUnmount() {

    }

    doInit() {
        const { selectType } = this.state;
        const { contentStore, params, location } = this.props;
        const { initDatas, getContacter, getSellChance } = contentStore;
        //一些初始化请求
        let fromUrl = {};
        if (location && JSON.stringify(location.query) !== "{}") {
            fromUrl = location.query;
        }
        const newBaseParams = { ...params, ...fromUrl, selectType: selectType };
        initDatas(newBaseParams);

        getContacter({ from: newBaseParams.from, customerId: newBaseParams.customerId });
        getSellChance({ from: newBaseParams.from, customerId: newBaseParams.customerId });
    }

    componentWillReceiveProps(nextProps) {
        const oldParams = this.props.params;
        const newParams = nextProps.params;
        if (!equal(oldParams, newParams)) {
            const { contentStore, params, location } = nextProps;
            const { initDatas, getContacter, getSellChance } = contentStore;
            let fromUrl = {};
            if (location && JSON.stringify(location.query) !== "{}") {
                fromUrl = location.query;
            }
            this.setState({ selectType: "info" }, () => {
                const { selectType } = this.state;
                const newBaseParams = { ...params, ...fromUrl, selectType: selectType };
                initDatas(newBaseParams);

                getContacter({ from: newBaseParams.from, customerId: newBaseParams.customerId });
                getSellChance({ from: newBaseParams.from, customerId: newBaseParams.customerId });
            });

        }
    }
    render() {
        const { type, contentStore, params } = this.props;
        const { verified, hasRight, contactLogs, contactLogsTotal, customerId, initDatas, loading,workplanvisible,isCreateWorkplan,workPlanId} = contentStore;
        const { rowHeight, contacterId, sellChanceId, value, isrefresh, ascSort, selectType, contactWayId,workPlanTab  } = this.state;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };
        // console.log("workplanvisible",workplanvisible)
        // console.log("isCreateWorkplan",isCreateWorkplan)
        // console.log("workPlanId",workPlanId)
        const account = WeaTools.ls.getJSONObj('theme-account'); //当前登陆人信息
        // if (verified && !hasRight) {
        //     return (<WeaAlertPage >
        //         <div style={{ color: '#000' }}>
        //             {getLabel(2012, "对不起，您暂时没有权限！")}
        //         </div>
        //     </WeaAlertPage>
        //     )
        // }
        if (verified) {
            let WorkPlanCreate = {};
            if (window.weaWorkplan) {
                WorkPlanCreate = weaWorkplan.com.WorkPlanCreate
            }
            return (
                <div className="customer-contact" >
                    <div>
                        <Row>
                            <Col span="24" style={{ marginBottom: "5px" }}>
                                <div style={{margin: '5px 0px'}}>
                                <Select value={contacterId} defaultValue={contacterId} onChange={(value) => this.handleChange("contacter", value)} style={{ width: "18%", marginLeft: '20px' }} size="small">
                                    <Option value="" key="1-1" title={getLabel(572, "联系人")}>-{getLabel(572, "联系人")}-</Option>
                                    {this.getContacterOption()}
                                </Select>
                                {type != "sellchance" &&
                                    <Select defaultValue={sellChanceId} onChange={(value) => this.handleChange("sellchance", value)} style={{ width: "20%", marginLeft: '10px' }} size="small" >
                                        <Option value="" key="1-1" title={getLabel(32922, "商机")}>-{getLabel(32922, "商机")}-</Option>
                                        {this.getSellChanceOption()}
                                    </Select>
                                }
                                <WeaError
                                    tipPosition='bottom'
                                    ref='contactWayError'
                                    style={{ width: "50%" }}
                                    error={getLabel(18214, "请选择") + getLabel(15858, "联系方式")}>
                                    <Select value={contactWayId}
                                        defaultValue={contactWayId}
                                        onChange={(value) => this.handleChange("contactWay", value)}
                                        style={{ width: "46%", marginLeft: '10px' }}
                                        size="small">
                                        <Option value="" key="1-1" title={getLabel(15858, "联系方式")}>-{getLabel(15858, "联系方式")}    - </Option>
                                        {this.getContactWay()}
                                    </Select>
                                </WeaError>
                                </div>
                                
                                <div style={{padding:"0 10px"}}>
                                    <WeaError tipPosition='bottom'
                                        ref='logInputError'
                                        style={{ width: "100%" }}
                                        error={getLabel(84370, "请填写联系记录！")}>
                                        {/* <Input type="textarea" ref="logInput"
                                            autofocus="autofocus" value={value} onChange={this.inputOnChange} placeholder={getLabel(84370, "请填写联系记录！")}
                                            rows={rowHeight} onFocus={() => this.textOnFocus(4)} /> */}
                                        <WeaTextarea
                                            // inputType="MULTILANG"
                                            // isBase64={true}
                                            ref="logInput"
                                            value={value}
                                            onChange={(v)=>this.inputOnChange(v)}
                                            placeholder={getLabel(84370, "请填写联系记录")+","+getLabel(523347,"限一万字以内!")}
                                            minRows={3}
                                            maxRows={6}
                                            stringLength={40000}
                                            style={{color:"#000"}}
                                        />
                                    </WeaError>
                                </div>
                                
                            </Col>
                        </Row>
                        <Row className="customer-contact-header">
                            <CrmSearchGroup needTigger={true} leftComponent={
                                <Col span="24" >
                                    <Button type="primary" size="small" onClick={() => this.submitContacts()}>{getLabel(615, "提交")}</Button>
                                    <Button type="primary" size="small" onClick={() => this.impContacts()}>{getLabel(128713,'EXCEL导入')}</Button>
                                    <Button type="ghost" size="small" onClick={() => { this.getCustomerInfo() }}>{getLabel(84371, "安排计划")}</Button>
                                    
                                </Col>
                            } rightComponent={getLabel(83273, "附加信息")} showGroup={false}>
                                {this.getFormItem()}
                                <WeaFormItem
                                    label={getLabel(22194, "相关附件")}
                                    labelCol={{ span: 5 }}
                                    wrapperCol={{ span: 14 }}  >
                                    <WeaUpload
                                        key={isrefresh}
                                        uploadId="relatedfile"
                                        uploadUrl="/api/crm/common/fileUpload"
                                        category="0,0,0"
                                        autoUpload={true}
                                        showBatchLoad={false}
                                        showClearAll={false}
                                        multiSelection={true}
                                        datas={[]}
                                        onChange={this.fileUploadBack}
                                    // onUploading={(state)=>{}}
                                    />
                                </WeaFormItem>
                                <WeaFormItem
                                    label={getLabel(20001, "上传图片")}
                                    labelCol={{ span: 5 }}
                                    wrapperCol={{ span: 14 }}  >
                                    <WeaUpload
                                        key={isrefresh}
                                        title={getLabel(125080, '选择图片')}
                                        uploadId="relatedimgs"
                                        uploadUrl="/api/crm/common/fileUpload"
                                        multiSelection={true}
                                        category="0,0,0"
                                        limitType="png,gif,jpeg,jpg,bmp"
                                        datas={[]}
                                        onChange={(ids, list) => {
                                            if (list && list.length) {
                                                this.imgsUploadBack(ids);
                                            }
                                        }}
                                    >
                                    </WeaUpload>
                                </WeaFormItem>
                            </CrmSearchGroup>
                        </Row>
                        <div className="customer-contact-sort">
                            <div className="customer-contact-sort-tab">
                                <Radio.Group defaultValue={selectType} value={selectType} onChange={(e) => {
                                    const v = e.target.value;
                                    this.setState({ selectType: v }, () => {
                                        if (v == "plan") {
                                            this.sortByAsc();
                                        } else {
                                            this.sortByDesc();
                                        }
                                    });
                                }}>
                                    <Radio.Button value="info">{getLabel(17532, "联系记录")}</Radio.Button>
                                    <Radio.Button value="plan">{getLabel(16402, "联系计划")}</Radio.Button>
                                </Radio.Group>
                            </div>
                            <div style={{ width: "65px" }}>
                                <div onClick={this.sortByAsc} className="customer-contact-sort-asc" style={{ background: `url(/images/ecology9/crm/icon_sequence_${ascSort ? "" : "h_"}e9.png)` }}></div>
                                <div onClick={this.sortByDesc} className="customer-contact-sort-asc" style={{ background: `url(/images/ecology9/crm/icon_reverse_${ascSort ? "h_" : ""}e9.png)` }}></div>
                            </div>
                            <Spin spinning={false} />
                        </div>
                    </div>
                    <div className="customer-contact-content" onClick={this.textOnBlur}>
                        <div id="viewLogs" style={{ height: "100%", paddingBottom: "10px", overflowY:"scroll" }}>
                            {/* <WeaNewScroll height={"100%"} children={<ViewContactLog data={toJS(contactLogs)} total={contactLogsTotal} pageChange={(num) => { contentStore.getNextCusContactList({ pageNum: num }) }} />} /> */}
                            <ViewContactLog 
                            data={toJS(contactLogs)}
                             total={contactLogsTotal} 
                            
                             store={contentStore}

                             pageChange={(num) => { contentStore.getNextCusContactList({ pageNum: num }) }} />
                        </div>
                    </div>
                    {window.weaWorkplan && (
                        <WorkPlanCreate
                            type={ (workPlanId ==""&&isCreateWorkplan)?"create":"preview"}//新建为'create',查看为'preview',编辑edit,共享share
                            // visible={this.state.visible}//显隐受控
                            visible={workplanvisible}
                            doClose={() => {
                                this.setWorkPlanVisisble(false);
                                // let p = {from:"all",customerId:params.customerId}
                                // if(params.sellchanceId){
                                //     p.sellchanceId = params.sellchanceId
                                // }
                                // initDatas(p);
                                this.textOnBlur();
                                this.setState({ value: "", selectType: "plan" });
                                this.sortByAsc();
                                // console.log("hello world")
                            }
                            }//关闭回调
                            onlyClose={() => { this.setWorkPlanVisisble(false) }}//关闭回调,只做关闭操作
                            workPlanId={(workPlanId !=""&&!isCreateWorkplan)?workPlanId:""} //日程id，1查看日程时用到
                            createConditionParams={[]}//创建的默认值日期和时间,没有传[]
                            activeKey={workPlanTab} //查看页面显示的面板1是基本信息，7是相关交流
                            changeTab={
                                //查看页面切换面板的回调
                                (key) => {
                                    this.setState({ workPlanTab: key });
                                }
                            }
                            selectUser={account && account.userid}//新建日程的创建人id
                            workPlanTypeOptions={3}//客户模块的新建日程，普通新建传'',客户新建传3
                            crmIDs={workplanvisible&&isCreateWorkplan&& this.state.crmArr}//通过客户模块新建日程，并自动带出相关客户,[{'id':'','name':''}]
                            description={this.state.value}//客户模块需求，支持新建时传入的'基本信息-内容'
                        />
                    )}

                </div>
            )
        }
        return <div></div>
    }

    getContactWay() {
        const { contactWays = [] } = this.props.contentStore;
        let children = [];
        toJS(contactWays).map(item => {
            children.push(<Option value={item.id} key={item.id} title={item.name}>{item.name}</Option>)
        })
        return children
    }
    getContacterOption() {
        const { contacterInfo } = this.props.contentStore;
        let children = [];
        toJS(contacterInfo).map(item => {
            children.push(<Option value={item.contacterid} key={item.contacterid} title={item.firstname}>{item.firstname}</Option>)
        })
        return children
    }
    getSellChanceOption() {
        const { sellChanceInfo } = this.props.contentStore;
        let children = [];
        toJS(sellChanceInfo).map(item => {
            children.push(<Option value={item.sellchanceid} key={item.sellchanceid} title={item.subject}>{item.subject}</Option>)
        })
        return children
    }
    textOnFocus = (h) => {
        this.setState({
            rowHeight: h
        })
        this.refs.logInput.refs.input.focus();
    }
    textOnBlur = () => {
        const { value } = this.state;
        if (!value) {
            this.setState({ rowHeight: 1 })
        }
    }
    getFormItem() {
        const { contentStore } = this.props;
        const { exchangeContent } = contentStore;
        const { isrefresh } = this.state;
        const items = [
            { label: getLabel(857, "相关文档"), title: getLabel(58, "文档"), type: 37, key: "relateddoc", show: true, num: isrefresh },
            { label: getLabel(1044, "相关流程"), title: getLabel(18015, "流程"), type: 152, key: "relatedwf", show: true, num: isrefresh },
            { label: getLabel(782, "相关项目"), title: getLabel(101, "项目"), type: 135, key: "relatedprj", show: true, num: isrefresh },
        ];
        const formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 14 },
        };
        let group = [];
        items.map(item => {
            if (item.show) {
                group.push(
                    <WeaFormItem
                        label={item.label}
                        {...formItemLayout}>
                        <WeaBrowser key={item.num} type={item.type} title={item.title} hasAdvanceSerach={true} isSingle={false} onChange={(ids, names, datas) => this.browserOnchange(item.key, ids, names, datas)} />
                    </WeaFormItem>
                )
            } else {
                return;
            }
        })
        return group;
    }
    handleChange = (type, value) => {
        if (type == "contacter") {
            this.setState({ contacterId: value })
        } else if (type == "sellchance") {
            this.setState({ sellChanceId: value })
        } else if (type == "contactWay") {
            this.setState({ contactWayId: value })
        }
    }
    browserOnchange = (type, ids, names, datas) => {
        if (type == "relateddoc") {
            this.setState({ relateddoc: ids })
        } else if (type == "relatedwf") {
            this.setState({ relatedwf: ids })
        } else if (type == "relatedprj") {
            this.setState({ relatedprj: ids })
        }
    }
    fileUploadBack = (ids) => {
        this.setState({ relatedfile: `${ids}` });
    }
    imgsUploadBack = (ids) => {
        this.setState({ relatedimgs: `${ids}` });
    }
    inputOnChange = (e) => {
        this.setState({ value: e });
    }
    //提交
    submitContacts = () => {
        const { contacterId, sellChanceId, value, relateddoc, relatedwf, relatedprj, relatedfile, relatedimgs, contactWayId } = this.state;
        const { customerId, saveContacts } = this.props.contentStore;
        let { params } = this.props;
        if (value.trim()) {
            const content = {
                customerId: params.customerId || customerId,
                sellChanceId: sellChanceId || params.sellchanceId,
                contacterId: contacterId,
                //ContactInfo: value.replace(/(^\s*)|(\s*$)/g, "").replace(/\n/g, '<br>'),
                ContactInfo: value.replace(/\n/g, '<br>'),
                contactWayId: contactWayId,
                relateddoc: relateddoc,
                relatedwf: relatedwf,
                relatedprj: relatedprj,
                relatedfile: relatedfile,
                relatedimgs: relatedimgs,
            };
            if (!params) {
                params = { from: "all", customerId: customerId }
            }

            if (contactWayId != "") {
                saveContacts(content, { ...{ from: "all", customerId: customerId }, ...params });
                this.setState({
                    contacterId: "",
                    sellChanceId: "",
                    ascSort: true,
                    relatedfile: "",
                    relatedimgs: "",
                    relateddoc: "",
                    relatedwf: "",
                    relatedprj: "",
                    isrefresh: this.state.isrefresh + 1,
                    rowHeight: 1,
                    value: "",
                    contactWayId: "",
                });
            } else {
                this.refs.contactWayError.showError();
            }
        } else {
            this.refs.logInputError.showError();
            // Modal.info({
            //     title: getLabel(15172, "系统提示"),
            //     content: getLabel(84370, "请填写联系记录！"),
            //     okText: getLabel(33703, "确定")
            // });
        }
    }

    impContacts = () =>{
        const { contacterId, sellChanceId } = this.state;
        const { customerId } = this.props.contentStore;
        let { params } = this.props;
        const content = {
            customerId: params.customerId || customerId,
            sellchanceId: sellChanceId || params.sellchanceId,
            contacterId: contacterId,
        };
        if (!params) {
            params = { from: "all", customerId: customerId }
        }
        if(content.sellchanceId){
            window.open(`/spa/crm/static/index.html#/main/crm/contactImp?sellchanceId=${content.sellchanceId}`);
        }else{
            window.open(`/spa/crm/static/index.html#/main/crm/contactImp?customerId=${content.customerId}`);
        }
        
    }

    sortByDesc = () => {
        const { customerId, initDatas } = this.props.contentStore;
        const { params } = this.props;
        this.setState({ ascSort: true });
        initDatas({ ...params, customerId: customerId, orderway: 0, selectType: this.state.selectType });
    }
    sortByAsc = () => {
        const { customerId, initDatas } = this.props.contentStore;
        const { params } = this.props;
        this.setState({ ascSort: false });
        initDatas({ ...params, customerId: customerId, orderway: 1, selectType: this.state.selectType });
    }
    setWorkPlanVisisble = (bool) => {

        //this.setState({ visible: bool });
         const { setWorkplanVisible } = this.props.contentStore;
         setWorkplanVisible(bool)

    }
    getCustomerInfo = () => {
        const { contentStore, params } = this.props;
        const { customerId,setWorkplanVisible ,setWorkplanId} = contentStore;
        let crmArr = [];
        WeaTools.callApi('/api/crm/customer/getCrmNamesById', 'GET', { customerIds: params.customerId || customerId }).then(data => {
            if (data.status == "success") {
                crmArr.push({ 'id': params.customerId || customerId, 'name': data.datas });
                //this.setState({ visible: true, crmArr: crmArr });
                this.setState({ crmArr: crmArr },()=>{
                    setWorkplanVisible(true);
                    setWorkplanId("");
                });
            }
        })
        // return crmArr;
    }
}

export default WeaTools.tryCatch(React,
    props => <WeaErrorPage msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
    { error: "" }
)(CustomerContact);


// WEBPACK FOOTER //
// ./../src4js/pc4mobx/crm/components/public/CustomerContact.js